package com.jieli.stream.dv.running2.ui.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.jieli.stream.dv.running2.R;
import com.jieli.stream.dv.running2.bean.SettingItem;
import com.jieli.stream.dv.running2.ui.MainApplication;
import com.jieli.stream.dv.running2.ui.activity.GenericActivity;
import com.jieli.stream.dv.running2.ui.activity.me.APPAdvancedSettingActivity;
import com.jieli.stream.dv.running2.ui.activity.me.AppStorageManageActivity;
import com.jieli.stream.dv.running2.ui.activity.me.DeviceSettingActivity;
import com.jieli.stream.dv.running2.ui.activity.me.LanguageActivity;
import com.jieli.stream.dv.running2.ui.adapter.SettingAdapter;
import com.jieli.stream.dv.running2.ui.base.BaseFragment;
import com.jieli.stream.dv.running2.ui.widget.SwitchButton;
import com.jieli.stream.dv.running2.util.ClientManager;
import com.jieli.stream.dv.running2.util.Dbug;
import com.jieli.stream.dv.running2.util.PreferencesHelper;
import com.jieli.stream.dv.running2.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 设置
 * date : 2017/3/3
 */
public class SettingFragment extends BaseFragment {
    private static String tag = SettingFragment.class.getSimpleName();
    private ListView listView;
    private View mView;

    public static SettingFragment newInstance() {
        return new SettingFragment();
    }

    @Override
    public void onStart() {
        super.onStart();
        IntentFilter intentFilter = new IntentFilter(ACTION_LANGUAAGE_CHANGE);
        MainApplication.getApplication().registerReceiver(mBroadcastReceiver, intentFilter);
    }

    @Override
    public void onStop() {
        super.onStop();
        MainApplication.getApplication().unregisterReceiver(mBroadcastReceiver);
    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null)
                return;
            switch (action) {
                case ACTION_LANGUAAGE_CHANGE:
                    initUI();
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_setting, container, false);
        listView = (ListView) mView.findViewById(R.id.setting_list_view);
        // Dbug.e("SettingFragment",mApplication.getDeviceSettingInfo().toString());
        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();
        initUI();
    }

    private void initUI() {
        TextView title = (TextView) mView.findViewById(R.id.setting_top_tv);
        title.setText(R.string.tab_me);
        String[] names = getResources().getStringArray(R.array.setting_list);
        List<SettingItem> items = new ArrayList<>();
        int marginTop = (int) getResources().getDimension(R.dimen.list_marginTop);
        for (int i = 0; i < names.length; i++) {
            String name = names[i];
            if (!TextUtils.isEmpty(name)) {
                SettingItem item = new SettingItem<>();
                if (name.equals(getString(R.string.device_setting)) ||
                        name.equals(getString(R.string.app_storage_manager)) ||
                        //name.equals(getString(R.string.app_advanced_settings)) ||
                        name.equals(getString(R.string.about_app)) ||
                        name.equals(getString(R.string.help))
                        ) {
                    item.setType(0);
                } else if (name.equals(getString(R.string.language))) {
                    item.setType(0);

                    if (ClientManager.getClient().isConnected()) {
                        int index = 0;
                        String[] languages = getResources().getStringArray(R.array.language);
                        String languageCode = PreferencesHelper.getSharedPreferences(mApplication).getString(KEY_APP_LANGUAGE_CODE, "-1");
                        if (TextUtils.isDigitsOnly(languageCode)) {
                            index = Integer.parseInt(languageCode) - 1;
                        }
                        if (index > -1 && index < languages.length) item.setValue(languages[index]);
                    }/* else {
                        item.setValue(getResources().getConfiguration().locale.getDisplayName());
                        Dbug.e(tag, "DisplayName=" + getResources().getConfiguration().locale.getDisplayName());
                    }*/
                } else if (name.equals(getString(R.string.save_picture_in_phone))) {
                    item.setType(1);
                    item.setValue(PreferencesHelper.getSharedPreferences(getContext()).getBoolean(KEY_SAVE_PICTURE, false));
                    item.setOnSwitchListener(savePictureInPhoneOnSwitchListener);
                } else if (name.equals(getString(R.string.auto_download_the_photo_files))) {
                    item.setType(1);
                    item.setValue(PreferencesHelper.getSharedPreferences(getContext()).getBoolean(KEY_AUTO_DOWNLOAG_PICTURE, false));
                    item.setOnSwitchListener(downLoadPhotoOnSwitchListener);
                } else if (getString(R.string.app_advanced_settings).equals(name)) {
                    item.setType(0);
                }
                if (i == 0 || i == 1 || i == 3 || i == 4 || i == 5)
                    item.setMarginTop(marginTop);
                item.setName(name);
                items.add(item);
            }
        }
        listView.setAdapter(new SettingAdapter(getActivity().getApplicationContext(), items));
        listView.setOnItemClickListener(onItemClickListener);
    }


    /**
     * TODO 处理保存图片到手机逻辑
     */
    private SettingItem.OnSwitchListener savePictureInPhoneOnSwitchListener = new SettingItem.OnSwitchListener() {
        @Override
        public void onSwitchListener(SwitchButton v, SettingItem<Boolean> item, boolean isChecked) {
            PreferencesHelper.putBooleanValue(getContext(), KEY_SAVE_PICTURE, isChecked);
        }
    };
    /**
     * TODO 处理自动下载拍照文件逻辑
     */
    private SettingItem.OnSwitchListener downLoadPhotoOnSwitchListener = new SettingItem.OnSwitchListener() {
        @Override
        public void onSwitchListener(SwitchButton v, SettingItem<Boolean> item, boolean isChecked) {
            PreferencesHelper.putBooleanValue(getContext(), KEY_AUTO_DOWNLOAG_PICTURE, isChecked);
        }
    };

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SettingItem item = (SettingItem) listView.getAdapter().getItem(position);
            if (item.getType() == 0) {
                //获取显示value的textview
                TextView textView = (TextView) view.findViewById(R.id.item_setting_one_tv2);
                if (item.getName().equals(getString(R.string.device_setting))) {
                    if (ClientManager.getClient().isConnected()) {
                        DeviceSettingActivity.start(getActivity());
                    } else {
                        ToastUtil.showToastShort(getString(R.string.please_connect_device_to_use));
                    }
                } else if (item.getName().equals(getString(R.string.language))) {
                    if (ClientManager.getClient().isConnected()) {
                        LanguageActivity.start(getContext());
                    } else {
                        ToastUtil.showToastShort(getString(R.string.please_connect_device_to_use));
                    }
                } else if (item.getName().equals(getString(R.string.app_advanced_settings))) {
                    if (ClientManager.getClient().isConnected())
                        APPAdvancedSettingActivity.start(getContext());
                    else
                        ToastUtil.showToastShort(getString(R.string.please_connect_device_to_use));
                } else if (item.getName().equals(getString(R.string.about_app))) {
                    goToAbout();
                } else if (item.getName().equals(getString(R.string.help))) {
                } else if (item.getName().equals(getString(R.string.app_storage_manager))) {
                    AppStorageManageActivity.start(getContext());
                }
            } else {
                Dbug.e(tag, "item.getType() " + item.getType() +", position " + position);
            }
        }
    };


    private void goToAbout(){
        Intent intent = new Intent(getActivity(), GenericActivity.class);
        intent.putExtra(KEY_FRAGMENT_TAG, ABOUT_FRAGMENT);
        startActivity(intent);
    }

}
